package com.list88zhu.common.rxhttp.http.exception;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONPathException;

import java.net.ConnectException;
import java.net.SocketException;
import java.net.UnknownHostException;

import freemarker.core.ParseException;
import retrofit2.HttpException;

/**
 * projectName rxretrofit
 * date 2017/7/7
 * description 网络异常处理
 */

public class FactoryException {
    private static final String HttpException_MSG = "网络错误";
    private static final String ConnectException_MSG = "链接异常，请检查您的网络";
    private static final String JSONException_MSG = "fastjeson解析失败";
    private static final String UnknownHostException_MSG = "无法解析该域名";

    public static ApiException analysisException(Throwable throwable){
        ApiException apiException = new ApiException(throwable);
        if(throwable instanceof HttpException){
            apiException.setCode(CodeException.HTTP_ERROR);
            apiException.setMessage(HttpException_MSG);
        }else if(throwable instanceof HttpResultException){
            HttpResultException exception = (HttpResultException) throwable;
            apiException.setCode(CodeException.RUNTIME_ERROR);
            apiException.setMessage(exception.getMessage());
        }else if(throwable instanceof ConnectException || throwable instanceof SocketException || throwable instanceof retrofit2.adapter.rxjava.HttpException){
             /*链接异常*/
            apiException.setCode(CodeException.HTTP_ERROR);
            apiException.setMessage(ConnectException_MSG);
        }else if(throwable instanceof JSONPathException || throwable instanceof JSONException || throwable instanceof ParseException){
            apiException.setCode(CodeException.JSON_ERROR);
            apiException.setMessage(JSONException_MSG);
        }else if (throwable instanceof UnknownHostException){
            /*无法解析该域名异常*/
            apiException.setCode(CodeException.UNKOWNHOST_ERROR);
            apiException.setMessage(UnknownHostException_MSG);
        } else {
            /*未知异常*/
            apiException.setCode(CodeException.UNKNOWN_ERROR);
            apiException.setMessage(throwable.getMessage());
        }
        return apiException;
    }
}
